package net.jxtz.jxtzos.spider;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.entity.spider.SpiderLogServe;
import net.jxtz.jxtzos.service.spider.SpiderLogServeService;
import net.jxtz.jxtzos.util.StampToDateAndDateToStamp;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 *
 * 定时任务执行
 *
 * @author lmh
 * @version 1.0
 * @date 2021-09-15 14:43
 */

@Component
@Slf4j
public final class SpiderSchedule {

    private final static int INIT_DELAY = 7 * 60 * 60 * 1000;
    private final static long FIXED_DELAY = 24 * 60 * 60 * 1000;
    private final static int DAY = 1;
    private final static long MINUS_DAY = 7L;
    private final static String SCHEDULED_SPIDER_NAME = "周自动爬取";

    private final ExecutorService executorService = new ThreadPoolExecutor(5, 10, 60, TimeUnit.MINUTES, new LinkedBlockingQueue<>(), r -> {
        Thread thread = new Thread(r);
        thread.setName("spiderSchedule");
        return thread;
    });

    private final SpiderFactory instance = SpiderFactory.getInstance();

    @Scheduled(initialDelay = INIT_DELAY, fixedDelay = DAY * FIXED_DELAY)
    public void week() throws InterruptedException {
        // 先去数据库里查有没有未完成的请求（预约请求）
        List<SpiderLogServe> isSuccess = spiderLogServeService.list(new QueryWrapper<SpiderLogServe>().eq("is_execute", false));
        if (isSuccess.size() > 0) {
            for (SpiderLogServe success : isSuccess) {
                if (success.getUserId() != 0L) {
                    executorService.execute(() -> instance.invokeSpiderStart(success.getSpiderCode(), success, new SpiderDefinition()));
                    success.setExecute(true);
                }
            }

            spiderLogServeService.updateBatchById(isSuccess);
        }

        List<SpiderLogServe> list = spiderLogServeService.list(new QueryWrapper<SpiderLogServe>().orderByDesc("create_time").eq("user_id", 0L));

        SpiderLogServe id = null;
        if (list.size() <= 0) {
            // 第一次则直接创建一个
            id = new SpiderLogServe();
            id.setSpiderName(SCHEDULED_SPIDER_NAME);
            id.setUserId(0L);
            id.setExecute(false);
            spiderLogServeService.save(id);
        }else {
            id = list.get(0);
            log.info(id.toString());
        }

        String s = StampToDateAndDateToStamp.timeStampToLocalDateTime(id.getCreateTime());
        boolean expireOnDay = StampToDateAndDateToStamp.isExpireOnDay(s, MINUS_DAY);
        // expireDay == true 则说明已过期 可以执行
        if (expireOnDay) {
            List<SpiderDefinition> spiderKey = instance.getSpiderKey();
            for (SpiderDefinition spiderDefinition : spiderKey) {
                executorService.execute(() -> instance.invokeSpiderStart(spiderDefinition.getSpiderCode(), new SpiderLogServe(spiderDefinition.getSpiderName(), spiderDefinition.getSpiderCode(), 0L), spiderDefinition));
            }

            id.setExecute(true);
            spiderLogServeService.updateById(id);

            SpiderLogServe spiderLogServe = new SpiderLogServe();
            spiderLogServe.setSpiderName(SCHEDULED_SPIDER_NAME);
            spiderLogServe.setExecute(false);
            spiderLogServe.setUserId(0L);
            spiderLogServeService.save(spiderLogServe);
        }
    }

    private final SpiderLogServeService spiderLogServeService;

    public SpiderSchedule(SpiderLogServeService spiderLogServeService) {
        this.spiderLogServeService = spiderLogServeService;
    }

}
